<?php

	/**
	 * 添加订单前置操作
	 * 处理订单详情
	 */
	function order_add_before($model, $action){
		
		$model->orderno = createOrderNo();
		
		//处理订单地址
		$model = order_add_address($model, $action);
		//处理订单详情
		$model = order_add_detail ($model, $action);
		//处理订单金额
		$model = order_calc_money ($model);
		
		return $model;
	}
	
	
	
	/**
	 * 处理订单套餐和计费规则[package:1是|typeid:3计次|4计时]
	 */
	function dealOrderDetail($model, $cart){
		
		$package = $cart['package'];
		if($package == 1){
			$model->dealOrderPackage($cart);
		}else{
			$typeid = $cart['typeid'];
			if($typeid == 3){
				$model->dealOrderNumber($cart);
			}elseif($typeid == 4){
				$model->dealOrderTime($cart);
			}
		}
	}
	
	/**
	 * 添加订单地址
	 */
	function order_add_address($model,$action){
		
		$model->shipfee = 0;
		return $model;
	}
	
	/**
	 * 计算优惠金额
	 */
	function order_calc_money($model){
		
		$cardfee = 0;
		//$rent    = $model->rent;
		$model->cardfee = $cardfee;
		$model->totalfee = $model->orderfee + $model->shipfee - $cardfee;
		return $model;
	}
	/**
	 * 订单详情后置操作
	 */
	function orderdetail_edit_before($model) {
		
		//更新订单详情的菜品属性
		ordre_detail_insert($_POST['flag'],$_POST['orderno']);
		order_detail_update($_POST['amount'],$_POST['ask'],$_POST['orderno']);
		
		//计算所有订单详情总价返回该总价
		$total = ordre_detail_select($_POST);
		
		//返回订单相关金额
		$order = M('Order')->where("orderno='".$_POST['orderno']."'")->find();
		
		$model->orderfee   = $total['drinkfee']+$total['dishesfee']+$order['shipfee'];  //订单总金额
		$model->dishesfee  = $total['dishesfee'];                                       //菜品总金额
		$model->drinkfee   = $total['drinkfee'];                                        //菜品总金额
		$model->settlefee  = $total['settlefee'];                                      //结算金额-成本金额
		$model->receivefee = $model->orderfee-$model->settlefee;                       //实收金额
		
		return $model;
	}


	/**
	 * 根据订单编号查询所有订单
	 */
	function ordre_detail_select($array){

		//$map['flag']    = 'dishes';
		$map['orderno'] = $array['orderno'];
		
		$total = array();
		$data  = M("OrderDetail")->where($map)->select();
		
		foreach($data as $k=>$v){
			if($v['flag'] == 'dishes'){
				$total['attrfee']   += $v['smprice'];
				$total['dishesfee'] += $v['total']; //菜品总金额
			}else{
				$total['drinkfee']  += $v['total']; //饮品总金额
			}                       
			//$total['settlefee'] += $v['mprice']*$v['amount']+$v['smprice'];   //结算金额
			//$total['settlefee'] += $v['mprice']*$v['amount'];                 //结算金额
			$total['settlefee'] += ($v['mprice']+$v['smprice'])*$v['amount'];    //结算金额
		}
		
		return $total;
	}
	
	/**
	 * 更新订单详情中的订单数量和订单备注
	 */
	function order_detail_update($amount,$ask,$orderno){
		
		$model = M('OrderDetail');
		
		foreach($ask as $m=>$n){
			$cat['id']  = $m;
			$cat['ask'] = $n;
			$cat['content'] = $n;
			$model->save($cat);
		}
		
		foreach($amount as $k=>$v){
			$one = $model->find($k);
			
			$map['id']      = $k;
			$map['amount']  = $v;
			$map['total']   = $v*$one['price'];
			//$map['smprice'] = $v*$one['smprice'];
			$model->save($map);
		}
	}
	
	/**
	 * 循环订单属性将各个商品的属性插入订单详情表
	 */
	function ordre_detail_insert($array,$orderno){
		
		$arr   = array();
		$model = M("OrderDetail");
		
		foreach ($array as $k=>$v){
			$propPrice = 0;
			$chengben  = 0;
			$chenfee   = 0;
			$attr = array_remove($array[$k]); //去除掉数组中值为空的数组
			foreach($attr as $m=>$n){
				if($n['xtype']==1){
					foreach ($n['config'] as $x=>$y){
						$arr[]    = $k;
						$mprice   = $n['config'][$x]['mprice'];  //销售价格
						$chenfee  = $n['config'][$x]['amprice']; //成本价格
						if($mprice){$propPrice += $mprice;}  //属性销售总价
						if($chenfee){$chengben += $chenfee;} //成本总价
					}
				}else{
					if($n['config']){
						foreach ($n['config'] as $x=>$y){
							$arr[]      = $k;
							$num        = $n['config'][$x]['num'];
							$smprice    = $n['config'][$x]['mprice'];  //销售价格
							$chenfee    = $n['config'][$x]['amprice']; //成本价格
							$num        = $num?$num:1;
							$propPrice += $num*$smprice; //属性销售总价
							$chengben  += $num*$chenfee; //成本总价
						}
					}
				}
			}
			
			$part     = array_level_str($attr);
			$attr_bak = json_encode($attr);              //将数组转换成字符串
			
			$detail = $model->find($k);                  //订单详情
			$dishes = M('Dishes')->find($detail['pid']); //菜品详情
			
			$map['price']   = $dishes['sprice']+$propPrice;
			$map['mprice']  = $dishes['mprice'];
			$map['smprice'] = $chengben;
			$map['part']    = $part;
			$map['attr']    = $attr_bak;
			$map['total']   = $map['price']*$detail['amount'];
			$map['id']      = $k;
			$model->save($map);      //修改订单详情
			Log::write('propPrice2:'.$model->getLastSql()."|arr:".var_export($map,true),Log::DEBUG);
		}
		
		/*$ids = $model->where("orderno='$orderno'")->select();
		foreach($ids as $k=>$v){
			if(!in_array($v['id'],$arr)){
				$cat['attr']  = "";
				$cat['part']  = "";
				$cat['id']    = $v['id'];
				$cat['price'] = $v['dprice'];
				$cat['total'] = $v['dprice']*$v['amount'];
				$cat['smprice'] = 0;
				$model->save($cat);
			}
		}*/
	}
	
	/**
	 * 移除掉数组中值为空的元素
	 */
	function array_remove($array){
		foreach ($array as $k=>$v){
			foreach ($v['config'] as $z=>$y){
				foreach($y as $m=>$n){
					if(empty($n)){
						unset($array[$k]["config"][$z][$m]);
					}
				}
				if(empty($array[$k]["config"][$z])){
					unset($array[$k]["config"][$z]);
				}
			}
			if(empty($array[$k]['config'])){
				unset($array[$k]);
			}
		}
		return $array;
	}
	
	/**
	 * 移除掉数组中值为空的元素
	 */
	function array_level_str($array){
			
		foreach ($array as $k=>$v){
			$str = $k.":";
			foreach ($v['config'] as $z=>$y){
				$str .= $z.",";
			}
			$string .= $str."|";
		}
		return $string;
	}
	
	/**
	 * 添加订单后置操作
	 * 操作角色对应的菜单
	 */
	function order_add_after($table, $id, $action) {
		
		$model = D("$table");
		$data  = $model->find($id);
		
		order_add_pay($data, $action);
	}
	/**
	 * 添加订单后置操作
	 * 添加订单详情
	 */
	function orderdetail_add_after($table, $id, $action) {
		
		//根据编号查询订单信息
		$order = M("Order");
		$data  = $order->find($id);
		
		//获取当前用户购物车信息
		$map['dataid']   = $data['dataid'];
		$map['tableid']  = $data['tableid'];
		$map['outletid'] = $data['outletid'];
		$map['admin']    = $data['admin'];
		$cart = M("Cart")->where($map)->order('id desc')->select();
		Log::write('orderdetail_add_after:'.M("Cart")->getLastSql().'|var:'.var_export($cart,true),Log::DEBUG);
		
		//修改用户信息返回用户编号和会员标识
		//$minfo = order_set_user($data);
		//添加订单详情
		$view = order_add_detail($cart,$data);
		//更新商品库存
		set_product_num($cart);
		//添加用户地址
		//user_add_address($data,$minfo);
		
		if($view){
			 //清除购物车
			 clear_mycart($map);
		}
	}
	
	/**
	 * 修改用户信息
	 */
	function order_set_user($data){
		
		$model = M("Member");
		//根据订单上的手机号码判断用是否存在
		$con['mobile'] = $data['mobile'];
		$member = $model->where($con)->find();
				
		if($member['id']){
			$minfo = array("tableid"=>"Member","dataid"=>$member['id']);
		}else{
			
			if($data['email']){
				$map['email']    = $data['email'];
				$map['username'] = $data['email'];
			}
			
			$map['address']  = $data['address'];
			$map['mobile']   = $data['mobile'];
			$map['realname'] = $data['username'];
			$map['remark']   = $data['content'];
			$map['isreg']    = 2;
			$map['addtime']  = time();
			
			$id    = $model->add($map);
			$flag  = $model->find($id);
			$minfo = array("tableid"=>"Member","dataid"=>$flag['id']);
		}
		//更新用户缓存
		session(C('USER_AUTH_KEY')  , $minfo['dataid']);
		session(C('USER_AUTH_TYPE') , $minfo['tableid']);
		
		//修改订单上的用户信息
		$order['id']      = $data['id'];
		$order['tableid'] = $minfo['tableid'];
		$order['dataid']  = $minfo['dataid'];
		$res = M("Order")->save($order);
		
		return $minfo;
	}
	
	/**
	 * 添加订单详情
	 */
	function order_add_detail($cart,$data){
		
		$map['outletid'] = $data['outletid'];
		$map['orderno']  = $data['orderno'];
		$map['dataid']   = $data['dataid'];
		$map['tableid']  = $data['tableid'];
		
		foreach ($cart as $k=>$v){
			
			$map['pno']    = $v['dishes_num'];
			$map['pid']    = $v['dishesid'];
			$map['entitle']= $v['entitle'];
			$map['title']  = $v['title'];
			$map['attr']   = $v['gnfr'];
			$map['part']   = $v['part'];
			$map['ask']    = $v['ask'];
			$map['flag']   = $v['flag'];
			$map['amount'] = $v['num'];
			$map['mprice'] = $v['mprice'];
			$map['dprice'] = $v['dprice'];
			$map['tprice'] = $v['tprice'];
			$map['smprice']= $v['psPrice'];
			$map['price']  = $v['xjprice']/$v['num'];
			$map['total']  = $v['xjprice'];
			$map['content']= $v['ask'];
			$map['addtime']= time();
			
			$view = M("OrderDetail")->add($map);
		}
		return $view;
	}
	
	/**
	 * 更新商品数量
	 * @param array $cart  购物车商品列表
	 */
	function set_product_num($cart){
		foreach ($cart as $k=>$v){
			
			$table = $v['flag']=='dishes'?"Dishes":"Drink";
			$model = M($table);
			
			$id   = $v['dishesid'];
			$data = $model->find($id);
			if($data){
				if($data['num']>=$v['num']){
					$map['num'] = $data['num']-$v['num'];
					$map['ordernum'] = $data['ordernum']+$v['num'];
				}else{
					$map['num'] = 0;
					$map['ordernum'] = $data['ordernum']+$data['num'];
				}
				$map['id']  = $data['id'];
				$model->save($map);
			}
		}
	}
	
	/**
	 * 添加用户地址
	 */
	function user_add_address($data,$minfo){
		
		//如果地址id为空的话，才执行添加地址操作
		//if(empty($data['addressid'])){
		//if(empty($_POST['memaddid']) && empty($_POST['addressid'])){
		if(empty($_POST['memaddid'])){
			
			if($data['addressid']){
				$one = M('Site')->find($data['addressid']);
				
				$map['longitude'] = $one['longitude'];
				$map['latitude']  = $one['latitude'];
				$map['addressid'] = $one['id'];
			}else{
				$map['longitude'] = $_POST['pointlng'];
				$map['latitude']  = $_POST['pointlat'];
			}
			
			$map['address']   = $data['address'];
			$map['mobile']    = $data['mobile'];
			$map['realname']  = $data['username'];
			$map['userid']    = $minfo['dataid'];
			$map['tableid']   = 'Member';
			$map['city']      = $data['city'];
			$map['addtime']   = time();
			
			M("Address")->add($map);
		}
	}
	
	/**
	 * 清除购物车
	 */
	function clear_mycart($map){
		
		return M("Cart")->where($map)->delete();
	}
	
	/**
	 * 添加订单支付
	 */
	function order_add_pay($data,$action){
		
		$data['title']    = $action->_req("title"   ,"trim","");//标题
		$data['content']  = $action->_req("content" ,"trim","");//说明
		$data['cardtype'] = $action->_req("cardtype","trim","");//优惠数据类型
		$data['cardid']   = $action->_req("cardid"  ,"intval","");//优惠数据编号
		
		//支付方式[Alipay|Tenpay|Bank|Paypal|Time即时付款]
		$data['payment']  = $action->_req("payment" ,"trim","Time");
		//付款类型[Cash现金|Bank刷卡|All现金+刷卡]
		$data['paytype']  = $action->_req("paytype" ,"trim","Cash");
		
		unset($data['id']);
		return M("OrderPay")->add($data);
		
	}
	
	/**
	 * 挂单后置操作
	 * 添加挂单单据详情
	 */
	function order_lock_after($table, $id, $action){
		
		$model = D("$table");
		$data  = $model->find($id);
		
		$map['tableid'] = $data['tableid'];
		$map['dataid']  = $data['dataid'];
		$map['company'] = $data['company'];
		
		$module = M("BillDetail");
		$list   = D("Cart")->listCart($map);
		
		foreach ($list as $k=>$v){
			unset($v['id']);
			$v['billid'] = $id;
			$v['dealno'] = $data['dealno'];
			
			$module->add($v);
		}
	}
	
	
	/**
	 * 添加计时项目前置操作
	 * 
	 */
	function order_timeAdd_before($model, $action){
		
		$orderno = createOrderNo();
		$model->orderno = $orderno;
		
		return $model;
	}
	
	/**
	 * 添加计时项目后置操作
	 */
	function order_timeAdd_after($table, $id, $action){
		
		$model = D("$table");
		$data  = $model->find($id);
		
		//添加计时订单详情
		order_timeAdd_detail($data, $action);
		//添加订单支付
		order_add_pay($data, $action);
	}
	
	/**
	 * 添加计时订单详情
	 */
	function order_timeAdd_detail($order, $action){
		
		$model = D("Order");
		
		$orderno = $order['orderno'];
		$dataid  = $order['dataid'];
		$tableid = $order['tableid'];
		$rent    = $order['rent'];
		$num     = $action->_req("num", "intval");
		$content = $action->_req("content","trim","");
		$time    = time();
		
		$pid  = $action->_req("pid", "intval");
		$item = M("Product")->find($pid);
		$row  = $action->getParams();
		
		$row['pid']     = $item['id'];
		$row['pno']     = $item['pno'];
		$row['title']   = $item['title'];
		$row['typeid']  = $item['typeid'];
		$row['price']   = $item['sprice'];
		$row['total']   = $item['sprice'];
		
		$row['orderno'] = $orderno;
		$row['size']    = 1;
		$row['amount']  = 1;
		$row['package'] = 2;
		$row['addtime'] = $time;
		$row['dataid']  = $dataid;
		$row['tableid'] = $tableid;
		$row['content'] = $content;
		
		$module  = M("OrderDetail");
		$row['id']  = $module->add($row);
		
		$data['rent']   = $rent;
		$data['begin']  = $time;
		$data['amount'] = $num;
		$data['pay']    = 1;
		$data['isdel']  = 3;
		if($num){
			$data['plan'] = $num*3600;
		}
		$model->dealOrderTime($row,$data);
	}